package com.ruoyi.web.service.impl;

import com.ruoyi.web.service.ICommentAfterServiceService;
import com.ruoyi.web.mapper.CommentAfterServiceMapper;
import com.ruoyi.web.util.ChineseTextAnalyzer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 评论与售后分析服务实现类
 * 
 * @author ruoyi
 */
@Service
public class CommentAfterServiceServiceImpl implements ICommentAfterServiceService {

    @Autowired
    private CommentAfterServiceMapper commentAfterServiceMapper;
    
    // @Autowired
    // private ChineseTextAnalyzer textAnalyzer;

    @Override
    public Map<String, Object> getCommentStatistics(String startTime, String endTime, Long goodId, String ratingRange) {
        try {
            // 设置默认时间范围
            if (startTime == null || startTime.isEmpty()) {
                startTime = LocalDateTime.now().minusDays(30).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            if (endTime == null || endTime.isEmpty()) {
                endTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }

            // 封装参数
            Map<String, Object> params = new HashMap<>();
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            params.put("goodId", goodId);
            params.put("ratingRange", ratingRange);

            return commentAfterServiceMapper.selectCommentStatistics(params);
        } catch (Exception e) {
            throw new RuntimeException("获取评论统计数据失败", e);
        }
    }

    @Override
    public Map<String, Object> getCommentRatingDistribution(String startTime, String endTime, Long goodId) {
        try {
            // 设置默认时间范围
            if (startTime == null || startTime.isEmpty()) {
                startTime = LocalDateTime.now().minusDays(30).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            if (endTime == null || endTime.isEmpty()) {
                endTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }

            // 封装参数
            Map<String, Object> params = new HashMap<>();
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            params.put("goodId", goodId);

            return commentAfterServiceMapper.selectCommentRatingDistribution(params);
        } catch (Exception e) {
            throw new RuntimeException("获取评论评分分布失败", e);
        }
    }

    @Override
    public Map<String, Object> getCommentKeywords(String startTime, String endTime, Long goodId, Integer topN) {
        try {
            // 设置默认时间范围
            if (startTime == null || startTime.isEmpty()) {
                startTime = LocalDateTime.now().minusDays(30).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            if (endTime == null || endTime.isEmpty()) {
                endTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }

            // 封装参数
            Map<String, Object> params = new HashMap<>();
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            params.put("goodId", goodId);
            params.put("topN", topN != null ? topN : 20);

            // 获取关键词数据
            List<Map<String, Object>> keywordsList = commentAfterServiceMapper.selectCommentKeywords(params);
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("keywords", keywordsList);
            
            // 统计情感分析数据
            Map<String, Integer> sentimentStats = new HashMap<>();
            sentimentStats.put("positive", 0);
            sentimentStats.put("negative", 0);
            sentimentStats.put("neutral", 0);
            
            for (Map<String, Object> keyword : keywordsList) {
                String sentiment = (String) keyword.get("sentiment");
                if (sentiment != null) {
                    sentimentStats.put(sentiment, sentimentStats.get(sentiment) + 1);
                }
            }
            result.put("sentimentStats", sentimentStats);

            return result;
        } catch (Exception e) {
            throw new RuntimeException("获取评论关键词分析失败", e);
        }
    }

    @Override
    public Map<String, Object> getNegativeCommentAlert(String startTime, String endTime, Long goodId, Double threshold) {
        try {
            // 设置默认时间范围
            if (startTime == null || startTime.isEmpty()) {
                startTime = LocalDateTime.now().minusDays(7).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            if (endTime == null || endTime.isEmpty()) {
                endTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }

            // 封装参数
            Map<String, Object> params = new HashMap<>();
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            params.put("goodId", goodId);
            params.put("threshold", threshold != null ? threshold : 3.0);

            Map<String, Object> result = commentAfterServiceMapper.selectNegativeCommentAlert(params);
            
            // 对负面评论进行情感分析
            List<String> negativeComments = (List<String>) result.get("negativeComments");
            if (negativeComments != null && !negativeComments.isEmpty()) {
                List<Map<String, Object>> analysisResults = new ArrayList<>();
                for (String comment : negativeComments) {
                    Map<String, Object> analysis = new HashMap<>();
                    analysis.put("comment", comment);
                    // 暂时返回模拟情感分析数据
                analysis.put("sentiment", "positive");
                // analysis.put("sentiment", textAnalyzer.analyzeSentiment(comment));
                    analysisResults.add(analysis);
                }
                result.put("sentimentAnalysis", analysisResults);
            }

            return result;
        } catch (Exception e) {
            throw new RuntimeException("获取负面评价预警失败", e);
        }
    }

    @Override
    public Map<String, Object> getAfterServiceStatistics(String startTime, String endTime, String status, String serviceType) {
        try {
            // 设置默认时间范围
            if (startTime == null || startTime.isEmpty()) {
                startTime = LocalDateTime.now().minusDays(30).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            if (endTime == null || endTime.isEmpty()) {
                endTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }

            // 封装参数
            Map<String, Object> params = new HashMap<>();
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            params.put("status", status);
            params.put("serviceType", serviceType);

            return commentAfterServiceMapper.selectAfterServiceStatistics(params);
        } catch (Exception e) {
            throw new RuntimeException("获取售后统计数据失败", e);
        }
    }

    @Override
    public Map<String, Object> getAfterServiceCategory(String startTime, String endTime, String status) {
        try {
            // 设置默认时间范围
            if (startTime == null || startTime.isEmpty()) {
                startTime = LocalDateTime.now().minusDays(30).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            if (endTime == null || endTime.isEmpty()) {
                endTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }

            // 封装参数
            Map<String, Object> params = new HashMap<>();
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            params.put("status", status);

            return commentAfterServiceMapper.selectAfterServiceCategory(params);
        } catch (Exception e) {
            throw new RuntimeException("获取售后类型分布失败", e);
        }
    }

    @Override
    public Map<String, Object> getAfterServiceDuration(String startTime, String endTime, String serviceType) {
        try {
            // 设置默认时间范围
            if (startTime == null || startTime.isEmpty()) {
                startTime = LocalDateTime.now().minusDays(30).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            if (endTime == null || endTime.isEmpty()) {
                endTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }

            // 封装参数
            Map<String, Object> params = new HashMap<>();
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            params.put("serviceType", serviceType);

            return commentAfterServiceMapper.selectAfterServiceDuration(params);
        } catch (Exception e) {
            throw new RuntimeException("获取售后处理时长分析失败", e);
        }
    }

    @Override
    public Map<String, Object> getRadarChartData(String startTime, String endTime, Long goodId) {
        try {
            // 设置默认时间范围
            if (startTime == null || startTime.isEmpty()) {
                startTime = LocalDateTime.now().minusDays(30).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            if (endTime == null || endTime.isEmpty()) {
                endTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }

            // 封装参数
            Map<String, Object> params = new HashMap<>();
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            params.put("goodId", goodId);

            return commentAfterServiceMapper.selectRadarChartData(params);
        } catch (Exception e) {
            throw new RuntimeException("获取雷达图数据失败", e);
        }
    }

    @Override
    public Map<String, Object> getTreeChartData(String startTime, String endTime, String type) {
        try {
            // 设置默认时间范围
            if (startTime == null || startTime.isEmpty()) {
                startTime = LocalDateTime.now().minusDays(30).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            if (endTime == null || endTime.isEmpty()) {
                endTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }

            // 封装参数
            Map<String, Object> params = new HashMap<>();
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            params.put("type", type != null ? type : "category");

            return commentAfterServiceMapper.selectTreeChartData(params);
        } catch (Exception e) {
            throw new RuntimeException("获取树状图数据失败", e);
        }
    }

    @Override
    public Map<String, Object> getWordCloudData(String startTime, String endTime, Long goodId, Integer maxWords) {
        try {
            // 设置默认时间范围
            if (startTime == null || startTime.isEmpty()) {
                startTime = LocalDateTime.now().minusDays(30).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            if (endTime == null || endTime.isEmpty()) {
                endTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }

            // 封装参数
            Map<String, Object> params = new HashMap<>();
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            params.put("goodId", goodId);
            params.put("maxWords", maxWords != null ? maxWords : 50);

            Map<String, Object> result = commentAfterServiceMapper.selectWordCloudData(params);
            
            // 获取评论文本进行词云分析
            List<String> comments = (List<String>) result.get("comments");
            if (comments != null && !comments.isEmpty()) {
                // 使用中文文本分析器生成词云数据
                // 暂时返回模拟词云数据
            List<Map<String, Object>> wordCloudData = Arrays.asList(
                Map.of("text", "质量", "value", 50, "category", "positive"),
                Map.of("text", "服务", "value", 40, "category", "positive"),
                Map.of("text", "物流", "value", 30, "category", "neutral"),
                Map.of("text", "价格", "value", 25, "category", "positive"),
                Map.of("text", "包装", "value", 20, "category", "neutral")
            );
            // List<Map<String, Object>> wordCloudData = textAnalyzer.generateWordCloudData(comments, maxWords != null ? maxWords : 50);
                result.put("wordCloudData", wordCloudData);
            }

            return result;
        } catch (Exception e) {
            throw new RuntimeException("获取词云图数据失败", e);
        }
    }
}